﻿using Android.App;
using Android.Bluetooth;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace WSYmi.ConnectAct
{
    [BroadcastReceiver(Enabled = true)]
    public class BluetoothReceiver : BroadcastReceiver
    {
        public override void OnReceive(Context context, Intent intent)
        {
            string action = intent.Action;
            if (BluetoothDevice.ActionFound.Equals(action))
            {
                BluetoothDevice device = (BluetoothDevice)intent.GetParcelableExtra(BluetoothDevice.ExtraDevice);
                if (string.IsNullOrEmpty(device.Name) && string.IsNullOrEmpty(device.Alias)) return;

                MyDevice md = new MyDevice()
                {
                    Name = device.Name ?? device.Alias,
                    Address = device.Address,
                };
                var rssi = intent.GetShortExtra(BluetoothDevice.ExtraRssi, 0);
                md.Rssi = $"信号强度：{rssi}dBm({Math.Max(0, Math.Abs(100 - Math.Abs(rssi)))}%)";

                int index = ConnectActivity.DeviceList.FindIndex(x => x.Address == md.Address);
                if (index >= 0)
                {
                    ConnectActivity.DeviceList[index] = md;
                }
                else
                {
                    ConnectActivity.DeviceList.Add(md);
                }
                ConnectActivity.ConnAdapter.NotifyDataSetChanged();
            }
        }
    }
}